# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from myapp.forms import *
from django.views.generic import FormView
from myapp.models import PostAdd, Users
from django.conf import settings

def index(request):
    return render(request, 'index.html', {})

"""class PostAddView(FormView):
  postadd_form = PostAddForm
  template_name ='post_add_form.html'
  form_class = PostAddForm
  success_url = '/postadd/'
  def get_form(self, form_class):
    form = form(**self.get_form_kwargs())
    return form

  def form_valid(self, form):
    return  redirect("index")
"""
def PostAddView(request):
    if request.POST:
      form = PostAddForm(request.POST, request.FILES)
      if form.is_valid():
        #models.
        #pass
        #handle_uploaded_file(request.FILES['ad_image'])
        form.save()
    else:    
      form = PostAddForm()
    return render(request, 'post_add_form.html', locals())

def UserAdd(request, id=None):
    #if id:
    #  instance = get_object_or_404(gadd_users, id=id)
    #  form = UserRegisterForm(request.POST  or None, instance=instance) 
    if request.POST:
      form = UserRegisterForm(request.POST)
      if form.is_valid():
        print "This is save method"
        form.save()
    else:
      form = UserRegisterForm()
      comment_form = PostComment()
    return render(request, 'post_add_form.html', locals())

def AllAdds(request):
  if request.GET:
    pass
  all_adds = PostAdd.objects.all().order_by('-ad_latest_date')
  return render(request, 'adv/adds.html', locals())

def ViewAdd(request, add_id):
  if request.GET:
    pass
  add = PostAdd.objects.filter(id=add_id).values()
  if add:
    add = add[0]
  return render(request, 'adv/view_add.html', locals())

def MyComment(request):
  if request.POST:
    form = PostComment(request.POST)
    if form.is_valid():
      form.save()
    return HttpResponse("Comment is saved succesful.") 

def handle_uploaded_file(f):
    print f.name
    print settings.GET_IMAGE
    with open(settings.GET_IMAGE/f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
